package com.hty.PowerChat;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import pclientbackend.ChatClient;
import pclientbackend.Pclientbackend;
import pclientbackend.UserDataArray;
import pclientbackend.UserDataRet;

public class AddActivity extends AppCompatActivity {

    EditText editText_search;
    ImageButton imageButton_search;
    List<HashMap<String,Object>> list = new ArrayList<>();
    ListView listView;
    SimpleAdapter adapter;
    ChatClient chatClient;
    boolean isAdded = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle("添加");

        editText_search = findViewById(R.id.editText_search);
        imageButton_search = findViewById(R.id.imageButton_search);
        imageButton_search.setOnClickListener(new ClickListener());
        listView = findViewById(R.id.listView_add_search);
        adapter = new SimpleAdapter(AddActivity.this, list, R.layout.list_search_item, new String[]{"avatar", "name", "id", "age", "sex"}, new int[]{ R.id.imageView_avatar,   R.id.textView_name, R.id.textView_id, R.id.textView_age, R.id.textView_sex });
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, final View view, int position, long id) {
                final String sid = ((TextView) view.findViewById(R.id.textView_id)).getText().toString();
                for(int i=0; i<list.size(); i++) {
                    if(list.get(i).get("id").toString().equals(sid)) {
                        String s = "Id：\t" + list.get(i).get("id") + "\n用户名：\t" + list.get(i).get("name") + "\n" + "性别：\t" + list.get(i).get("sex") + "\n" + "年龄：\t" + list.get(i).get("age") + "\n签名：\t" + list.get(i).get("desc");
                        AlertDialog.Builder builder = new AlertDialog.Builder(AddActivity.this);
                        builder.setIcon(((ImageView)view.findViewById(R.id.imageView_avatar)).getDrawable());
                        builder.setTitle("用户");
                        builder.setMessage(s);
                        builder.setPositiveButton("添加", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                chatClient.addFriend(Long.parseLong(sid));
                                isAdded = true;
                                dialog.dismiss();
                            }
                        });
                        builder.setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                        AlertDialog dialog = builder.create();
                        dialog.show();
                        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLUE);
                        break;
                    }
                }
            }
        });

        String path = Environment.getExternalStorageDirectory().getPath() + File.separator + "PowerChat";
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String json = "{\"Host\":\"148.70.58.15:7889\"}";
        chatClient = Pclientbackend.getChatClient(path, json);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == android.R.id.home) { // ActionBar 返回键
            Intent intent = new Intent(AddActivity.this, MainActivity.class);
            intent.putExtra("isAdded", isAdded);
            //startActivity(intent);
            setResult(RESULT_OK, intent);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(AddActivity.this, MainActivity.class);
            intent.putExtra("isAdded", isAdded);
            //startActivity(intent);
            setResult(RESULT_OK, intent);
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    class ClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            switch (id) {
                case R.id.imageButton_search:
                    ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(editText_search.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    list.clear();
                    UserDataArray userDataArray = chatClient.searchPersons(editText_search.getText().toString());
                    UserDataRet userDataRet;
                    while((userDataRet = userDataArray.next()) != null){
                        HashMap<String, Object> listItem = new HashMap<>();
                        listItem.put("id", userDataRet.getId());
                        listItem.put("name", userDataRet.getName());
                        String sex = userDataRet.getSex()==1?"男":"女";
                        listItem.put("sex", sex);
                        listItem.put("age", userDataRet.getAge() + "岁");
                        listItem.put("desc", userDataRet.getDesc());
                        listItem.put("avatar", R.mipmap.avatar);
                        list.add(listItem);
                    }
                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }

}
